package com.ex04;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库的操作
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        String claName = "com.mysql.jdbc.Driver";
        try {
            Class.forName(claName);
            String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
            Connection connection = DriverManager.getConnection(url, "root", "root");
            Statement statement = connection.createStatement();
            String sqlInsert = "insert into user (user_name, age, password) values('wanWu2','11', 'Pass')";
            statement.execute(sqlInsert);

            String sqlSelect = "select * from user";
            ResultSet rs = statement.executeQuery(sqlSelect);
            List<Map<String, Object>> DBData = cacheData(rs);
            while (rs.next()) {
                System.out.println(rs.getString("username"));
                System.out.println(rs.getString("pwd"));
                System.out.println();//s out
            }
            rs.close();
            for (Map<String, Object> map : DBData) {
                System.out.println(map.get("user_name"));
                System.out.println(map.get("age"));
                System.out.println(map.get("sex"));
                System.out.println(map.get("password"));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将数据库的值缓存起来
     *
     * @param rs 结果
     * @return Map保存的结果
     * @throws SQLException 数据库异常
     */
    private static List<Map<String, Object>> cacheData(ResultSet rs) throws SQLException {
        List<Map<String, Object>> data = new ArrayList<>();
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()) {
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i + 1);

                Object value = rs.getObject(columnName);
                map.put(columnName, value);
            }
            data.add(map);
        }
        return data;
    }
}
